package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;

import luanvan.app.foodnote.library.AddressFromLatLng;
import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.HttpRetriever;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.TypeFood;
import luanvan.app.foodnote.library.UserFunctions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class EditFoodActivity extends SherlockActivity implements LocationListener {
	
	 private EditText txtPlaceName;
	 private EditText txtName;
	 private TextView txtAddress;
	 private EditText txtPhonenumber;
	 private EditText txtOthernotes;
	 private Spinner edtSinpinner;
	 
	 private Button btnEdit;
	 private Button btnDelete;
	 private Button btnGetAddresses;
	 
	 AlertDialogManager alertDialogManager = new AlertDialogManager();
	 
	 // User
	 UserFunctions userFunction;
	 String user;
	 
	 // Extra
	 String fid;
	 
     // Progress Dialog
     private ProgressDialog pDialog;
     
     // JSON parser class
     JSONParser jsonParser = new JSONParser();
     
     private static final int TEN_METERS = 10;
     private static final int TWO_MINUTES = 1000 * 60 * 2;
     
     private static final String url_food_detials = "http://10.0.2.2/foodnote/get_food_details.php";
     private static final String url_update_food = "http://10.0.2.2/foodnote/update_food.php";
     private static final String url_delete_food = "http://10.0.2.2/foodnote/delete_food.php";
     private static final String url_get_type_foods = "http://10.0.2.2/foodnote/get_type_foods.php";
     
    /* private static final String url_food_detials = "http://192.168.0.129/foodnote/get_food_details.php";
     private static final String url_update_food = "http://192.168.0.129/foodnote/update_food.php";
     private static final String url_delete_food = "http://192.168.0.129/foodnote/delete_food.php";
     private static final String url_get_type_foods = "http://192.168.0.129/foodnote/get_type_foods.php";*/
     
     // JSON Node names
     private static final String TAG_SUCCESS = "success";
     private static final String TAG_FOOD = "food";
     private static final String TAG_ID = "id";
     private static final String TAG_PLACE_NAME = "TEN_DIA_DIEM";
     private static final String TAG_NAME = "TEN_MON_AN";
     private static final String TAG_ADDRESS = "DIA_CHI";
     private static final String TAG_CITY = "THANH_PHO";
     private static final String TAG_PHONE = "SO_DIEN_THOAI";
     private static final String TAG_DESCRIPTION = "MO_TA";
     private static final String TAG_LATITUDE = "LATITUDE";
     private static final String TAG_LONGITUDE = "LONGITUDE";
     private static final String TAG_TYPE_FOOD_ID = "LOAI_MON_AN_id";
     
     private static final String TAG_UID = "unique_id";
     
     // Type Foods
     private static final String TAG_TYPE_ID = "id";
     private static final String TAG_TYPE_FOODS = "TEN_LOAI_MON_AN";
 
     private LocationManager locationManager;
     private double log;
 	 private double lat;
 	 
 	 private Location locat;
 	 boolean changeAddress = false;
 	 
 	 TypeFood mSelect;
 	 
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 requestWindowFeature(Window.FEATURE_LEFT_ICON);
		 super.onCreate(savedInstanceState);
		 setContentView(R.layout.edit_food);
		 getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.update);
		 
		 edtSinpinner = (Spinner) findViewById(R.id.edtLoaiMonAn);
		 
		 edtSinpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub
				mSelect = (TypeFood) parent.getItemAtPosition(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		 });
		 
		 btnEdit = (Button) findViewById(R.id.editFood);
		 btnDelete = (Button) findViewById(R.id.deleteFood);
		 btnGetAddresses = (Button) findViewById(R.id.btnGetAddresses);
		 
		 Intent i = getIntent();
		 fid = i.getStringExtra(TAG_ID);
		 
		 // Lay thong tin nguoi dung hien tai
		 userFunction = new UserFunctions();
		 user = userFunction.getUID(getApplicationContext());
		 
		 // Find Current Location
		 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		 Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		 if (location != null) {
			Log.d("Location", location.toString());
			onLocationChanged(location);
		 }
		 else {
			//showSettingsAlert();
		 }
		 
		 // Getting complete product details in background thread
         new GetFoodDetails().execute();
         
         btnEdit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new SaveFoodDetails().execute();
			}
		 });
	     
         btnDelete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showAlertDialog();
			}
         });
         
         btnGetAddresses.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new GetAddresses().execute(new Location[] {locat});
			}
		});
	 }
	 /**
	  * Hien thi thong bao xac nhan xoa mon an
	  */
	 private void showAlertDialog() {
	       AlertDialog.Builder dialog = new AlertDialog.Builder(EditFoodActivity.this);
	 
	        // Setting Dialog Title
	        dialog.setTitle("Xóa món ăn");
	 
	        // Setting Dialog Message
	        dialog.setMessage("Bạn có chắc xóa món ăn này?");
	 
	        // Setting alert dialog icon
	        dialog.setIcon(R.drawable.success);
	        
	        dialog.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					new DelectFood().execute();
				}
			}); 
	        dialog.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
	        AlertDialog alert = dialog.create();
	        alert.show();
	 }
	 
	 /**
	  * @author quanghoang
	  * Lay thong tin chi tiet mon an
	  */
	 class GetFoodDetails extends AsyncTask<String, String, String>{

		String type_food_id;
		List<TypeFood> loai_mon_an = new ArrayList<TypeFood>() ;
	    @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditFoodActivity.this);
            pDialog.setMessage("Loading food details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		@Override
		protected String doInBackground(String... params) {
			 
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					int success;
					
					try {
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("fid", fid));
						
						JSONObject json = jsonParser.makeHttpRequest(url_food_detials, "GET", params);
						// check your log for json response
                        Log.d("Single Food Details", json.toString());
                        
                        
                        success = json.getInt(TAG_SUCCESS);
                        if(success == 1){
                        	JSONArray foodObj = json.getJSONArray(TAG_FOOD);
                        	// get first product object from JSON Array
                        	JSONObject food = foodObj.getJSONObject(0);
                        	// product with this pid found
                            // Edit Text
                        	txtPlaceName = (EditText) findViewById(R.id.editPlaceName);
                        	txtName = (EditText) findViewById(R.id.editName);
                        	txtAddress = (TextView) findViewById(R.id.editAddress);
                        	txtPhonenumber = (EditText) findViewById(R.id.editPhone);
                        	txtOthernotes = (EditText) findViewById(R.id.editDescription);
                        	
                        	
                        	
                        	// display product data in EditText
                        	txtPlaceName.setText(food.getString(TAG_PLACE_NAME));
                        	txtName.setText(food.getString(TAG_NAME));
                        	txtAddress.setText(food.getString(TAG_ADDRESS)); //+ ", " + food.getString(TAG_CITY));
                        	//txtCities.setText(food.getString(TAG_CITY));
                        	txtPhonenumber.setText(food.getString(TAG_PHONE));
                        	txtOthernotes.setText(food.getString(TAG_DESCRIPTION));
                        	
                        	// get spinner
                        	type_food_id = food.getString(TAG_TYPE_FOOD_ID);
                        	
                        } else{
                            // product with pid not found
                        }
                        
                        
					} catch (JSONException e) {
                        e.printStackTrace();
                    }
					
					try {

						List<NameValuePair> params = new ArrayList<NameValuePair>();
						JSONObject json = jsonParser.makeHttpRequest(url_get_type_foods, "POST", params);
						// Check your log cat for JSON reponse
						Log.d("Load all type foods: ", json.toString());
						
						int success2 = json.getInt(TAG_SUCCESS);
						
						if(success2 == 1){
							JSONArray type_foods = json.getJSONArray("type_foods");
							
							for (int i = 0; i < type_foods.length(); i++){
								JSONObject c = type_foods.getJSONObject(i);
								
								String id = c.getString(TAG_TYPE_ID);
								String name_type = c.getString(TAG_TYPE_FOODS);
								
								TypeFood typeFood = new TypeFood();
								typeFood.setId(id);
								typeFood.setLoai_mon_an(name_type);
								
								loai_mon_an.add(typeFood);
							}
							
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
			return null;
		}
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					ArrayAdapter<TypeFood> adapter = new ArrayAdapter<TypeFood>(getApplicationContext(), 
							android.R.layout.simple_spinner_item, loai_mon_an);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					edtSinpinner.setAdapter(adapter);
					for(int i = 0; i < loai_mon_an.size(); i++){
						if(Integer.valueOf(type_food_id) == Integer.valueOf(loai_mon_an.get(i).getId())){
							edtSinpinner.setSelection(Integer.valueOf(loai_mon_an.get(i).getId()));
							break;
						}
					}
				}
			});
        }
		 
	 }
	 /**
	  * @author quanghoang
	  *	Luu thong tin mon an sau khi cap nhat
	  */
	 class SaveFoodDetails extends AsyncTask<String, String, String>{
		 int success;
	    @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditFoodActivity.this);
            pDialog.setTitle("Xin chờ");
            pDialog.setMessage("Đang cập nhật ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		@Override
		protected String doInBackground(String... args) {
			Log.d("ID", fid.toString());
			String placename = txtPlaceName.getText().toString();
			String name = txtName.getText().toString();
			String address = txtAddress.getText().toString();
			String city = cities;
			String phone = txtPhonenumber.getText().toString();
			String description = txtOthernotes.getText().toString();
			String latitude = String.valueOf(lat);
			String longitude = String.valueOf(log);
			
			if(!placename.isEmpty() && !name.isEmpty() && !address.isEmpty() && lat != 0 && log != 0){
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(TAG_ID, fid));
				
				
				params.add(new BasicNameValuePair(TAG_PLACE_NAME, placename));
				params.add(new BasicNameValuePair(TAG_NAME, name));
				params.add(new BasicNameValuePair(TAG_ADDRESS, address));
				params.add(new BasicNameValuePair(TAG_CITY, city));
				params.add(new BasicNameValuePair(TAG_PHONE, phone));
				params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
				params.add(new BasicNameValuePair(TAG_LATITUDE, latitude));
				params.add(new BasicNameValuePair(TAG_LONGITUDE, longitude));
				params.add(new BasicNameValuePair(TAG_TYPE_FOOD_ID, mSelect.getId()));
				
				params.add(new BasicNameValuePair(TAG_UID, user));
				params.add(new BasicNameValuePair("changeAddress", String.valueOf(changeAddress)));
				
				
				
	
	            // sending modified data through http request
	            // Notice that update product url accepts POST method
				JSONObject json = jsonParser.makeHttpRequest(url_update_food, "POST", params);
				Log.e("Save Food", json.toString());
				
				// check json success tag
				try {
					success = json.getInt(TAG_SUCCESS);
					if(success == 1){
						// successfully updated
	                    Intent i = getIntent();
	                    // send result code 100 to notify about product update
	                    setResult(100, i);
	                    finish();
					} 
				}
				catch (JSONException e) {
	                e.printStackTrace();
				} 
            }
			return null;
		}
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once product updated
            pDialog.dismiss();
            if(success == 3){
            	runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						alertDialogManager.showAlertDialog(EditFoodActivity.this, "Cập nhật món ăn", "Bạn không có quyền cập nhật món ăn này!", false);
					}
				});
            } else if(success == 2){
            	runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						alertDialogManager.showAlertDialog(EditFoodActivity.this, "Cập nhật món ăn", "Xin lỗi! Không thể cập nhật món ăn", false);
					}
				});
            } else if(success == 0){
            	runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						alertDialogManager.showAlertDialog(EditFoodActivity.this, "Cập nhật món ăn", "Dữ liệu yêu cầu còn thiếu", false);
					}
				});
            }
        }
		 
	 }
	 
	 /**
	  * @author quanghoang
	  *	Function xoa mon an
	  */
	 class DelectFood extends AsyncTask<String, String, String>{
		int success;
		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditFoodActivity.this);
            pDialog.setTitle("Please wait");
            pDialog.setMessage("Đang xóa ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
		@Override
		protected String doInBackground(String... args) {
			
			//String message;
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(TAG_ID, fid));
				params.add(new BasicNameValuePair(TAG_UID, user));
				JSONObject json = jsonParser.makeHttpRequest(url_delete_food, "POST", params);
				
				// check your log for json response
                Log.d("Delete Food", json.toString());
                success = json.getInt(TAG_SUCCESS);
                if(success == 1){
                	Intent i = getIntent();
                	setResult(100, i);
                	finish();
                }
			} catch (JSONException e) {
                e.printStackTrace();
            }
			return null;
		}
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();
            if(success == 0){
            	alertDialogManager.showAlertDialog(EditFoodActivity.this, "Xóa món ăn", "Không tìm thấy", false);
            } else if(success == 2){
            	alertDialogManager.showAlertDialog(EditFoodActivity.this, "Xóa món ăn", "Bạn không có quyền xóa món ăn này", false);
            } else if(success == 3){
            	alertDialogManager.showAlertDialog(EditFoodActivity.this, "Xóa món ăn", "Dữ liệu yêu cầu bị thiếu", false);
            }
            
        }
		 
	 }
	@Override
	protected void onResume() {
		super.onResume();
		//new GetAddresses().execute(new Location[] {locat});
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TWO_MINUTES, TEN_METERS, this); 
	}	
	@Override
	protected void onPause(){
		super.onPause();
		locationManager.removeUpdates(this);
	}
	@Override
	public void onLocationChanged(Location loc) {
		lat = loc.getLatitude();
		log = loc.getLongitude();
		this.locat = loc;
	}
	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	AddressFromLatLng addresFromLatLng;
	HttpRetriever http;
	String cities;
	ArrayList<String> listAddresses;
	String address = "";
	private class GetAddresses extends AsyncTask<Location, String, String>{

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EditFoodActivity.this);
            pDialog.setTitle("Please wait");
            pDialog.setMessage("Đang tìm địa chỉ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		@Override
		protected String doInBackground(Location... params) {
			final Location loc = params[0];
			listAddresses = new ArrayList<String>();
			addresFromLatLng = new AddressFromLatLng(loc);
	
			
			address = addresFromLatLng.Address();
			cities = addresFromLatLng.Address4();
			listAddresses = addresFromLatLng.listAddress();
			
			return null;
		}
		
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					ShowListAddresses(listAddresses);
				}
			});
        }
		
	}
	
	String presentAddress;
	private void ShowListAddresses(ArrayList<String> listAddresses){
		final String[] items = new String[listAddresses.size()];
		for (int i = 0; i < listAddresses.size(); i++){
			items[i] = listAddresses.get(i);
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(EditFoodActivity.this);
    	builder.setTitle("Địa điểm hiện tại");
    	builder.setIcon(R.drawable.mark_red);
    	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int item) {
				//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				presentAddress = items[item];
			}
		});
    	builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
    		
    		public void onClick(DialogInterface dialog, int id) {
    			//Toast.makeText(NewFoodActivity.this, "Success" + id, Toast.LENGTH_SHORT).show();
    			txtAddress.setText("");
    			txtAddress.setText(presentAddress);
    			changeAddress = true;
    		}
	    });
    	builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int id) {
    			dialog.dismiss();
    		}
	    });
    	AlertDialog alert = builder.create();
    	alert.show();
		
	}
	
	private void getTypeFood(){
		final List<TypeFood> loai_mon_an = new ArrayList<TypeFood>() ;
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONObject json = jsonParser.makeHttpRequest(url_get_type_foods, "POST", params);
		// Check your log cat for JSON reponse
		Log.d("Load all type foods: ", json.toString());
		
		try {
			int success = json.getInt(TAG_SUCCESS);
			if(success == 1){
				JSONArray type_foods = json.getJSONArray("type_foods");
				
				for (int i = 0; i < type_foods.length(); i++){
					JSONObject c = type_foods.getJSONObject(i);

					
					
					String id = c.getString(TAG_TYPE_ID);
					String name_type = c.getString(TAG_TYPE_FOODS);
					
					TypeFood typeFood = new TypeFood();
					typeFood.setId(id);
					typeFood.setLoai_mon_an(name_type);
					
					loai_mon_an.add(typeFood);
				}
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						ArrayAdapter<TypeFood> adapter = new ArrayAdapter<TypeFood>(getApplicationContext(), 
								android.R.layout.simple_spinner_item, loai_mon_an);
						adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						edtSinpinner.setAdapter(adapter);
					}
				});
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
